﻿/*
    Copyright (C) 2008, wj2929, wj2929@gmail.com

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    *KEEP THIS HEADER INFORMATION*
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using mjRegister.Entity;
using System.Net;
using System.Threading;
using System.IO;

namespace mjRegister.BAL
{
    //用户操作
    public class User
    {
        public CookieCollection cc = new CookieCollection();
        public UserInfo UserInfo { get; set; }
        RegexOptions options = ((RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline) | RegexOptions.IgnoreCase);

        public string Email { get; set; }
        public string Password { get; set; }

        public delegate void OnNotifyLogin(User user);
        public event OnNotifyLogin LoginNotifications;

        public delegate void OnNotifyLoginSuccess(User user);
        public event OnNotifyLoginSuccess LoginSuccessNotifications;

        public delegate void OnNotifyLoginFailure(User user);
        public event OnNotifyLoginFailure LoginFailureNotifications;

        public delegate void OnNotifyMessage(User user,string message);
        public event OnNotifyMessage MessageNotifications;

        public delegate void OnNotifyLogout(User user);
        public event OnNotifyLogout LogoutNotifications;

        //登录
        public bool Login(AccountInfo accountInfo)
        {
            UserInfo = accountInfo.UserInfo;
            bool b = Login(accountInfo.Email, accountInfo.Password);
            if (!b)
            {
                if (accountInfo.ActiveStatus != ActiveStatus.NoActive)
                {
                    accountInfo.ActiveStatus = ActiveStatus.NoActive;
                    Account.EditAccountInfo(accountInfo);
                }
            }
            else
            {
                if (UserInfo.AuthenticationCookieCollection != cc)
                {
                    UserInfo.AuthenticationCookieCollection = cc;
                    accountInfo.UserInfo = UserInfo;
                    Account.EditAccountInfo(accountInfo);
                }
            }
            return b;
        }

        public static SimpleUserInfo GetSimpleUserInfoFromUserInfo(UserInfo userInfo)
        {
            return new SimpleUserInfo 
            {
                uid = userInfo.uid,
                real_name = userInfo.real_name,
                real_name_unsafe = userInfo.real_name
            };
        }

        public IList<string> GetUserCodes()
        {
            IList<string> userCodes = new List<string>();
            string url = "http://www.kaixin001.com/friend/invite.php?group=&type=link&gid=0";
            HttpProc hp = new HttpProc(url, cc);
            string re = "usercode=(?<usercode>.*?)\\\"";
            string result = hp.Proc();
            if(Regex.IsMatch(result,re))
            {
                MatchCollection mc = Regex.Matches(result, re);
                for (int i = 0; i < mc.Count; i++)
                {
                    userCodes.Add(mc[i].Result("${usercode}"));
                }
            }
            return userCodes;
        }

        //判断是否已购买旧车回收卡
        public bool HasRecycleCard()
        {
            string url = "http://www.kaixin001.com/app/app.php?aid=1040&url=mycard.php";
            HttpProc hp = new HttpProc(url, cc);
            return Regex.IsMatch(hp.Proc(), "<span\\s+title=\\\".*?\\\">旧车回收卡</span>");
        }

        

        //获取Verify码
        public string GetVerify()
        {
            string url = "http://www.kaixin001.com/app/app.php?aid=1040&url=mycard.php";
            HttpProc hp = new HttpProc(url, cc);
            string ResStr1 = hp.Proc();
            string re = "var\\s+g_verify\\s*=\\s*\\\"(?<g_verify>.*?)\\\"";
            if (Regex.IsMatch(ResStr1, re))
            {
                return Regex.Match(ResStr1, re).Result("${g_verify}");
            }
            else
                return string.Empty;
        }

        //获取Verify及acc码
        public string GetVerify(ref string acc)
        {
            string url = "http://www.kaixin001.com/app/app.php?aid=1040";
            HttpProc hp = new HttpProc(url, cc);
            string ResStr1 = hp.Proc();
            acc = Helper.ScriptHelper.GetAccCode_Re(ResStr1);
            string re = "var\\s+g_verify\\s*=\\s*\\\"(?<g_verify>.*?)\\\"";
            if (Regex.IsMatch(ResStr1, re))
            {
                return Regex.Match(ResStr1, re).Result("${g_verify}");
            }
            else
                return string.Empty;
        }


        //获取车市数据
        public IList<CarMarketInfo> FetchCarMarketInfos(int delayConnect)
        {
            IList<CarMarketInfo> carMarketInfos = new List<CarMarketInfo>();
            string url = "http://www.kaixin001.com/app/app.php?aid=1040&url=market.php&start=0";
            HttpProc hp = new HttpProc(url, cc);
            string ResStr1 = hp.Proc();
            string re = "<div\\s+class=\\\"tac\\\".*?><img.*?>\\s*(?<carName>.*?)</div>\\s+\r\n<div\\s+class=\\\"tac\\\"" +
">价格：(?<carPrice>\\d+)元</div>\\s+\r\n<div\\s+class=\\\"tac\\\"><a\\s+href=\\\"javascript:purc" +
"hase\\((?<carId>\\d+)\\)";
            if (Regex.IsMatch(ResStr1, re, options))
            {
                string re1 = "\\s+.*<a\\s+href=\\\".*?(?<lastPageStart>\\d+)\\\".*?>末页</a>";
                int lastPageStart = int.Parse(Regex.Match(ResStr1, re1).Result("${lastPageStart}"));
                MatchCollection mc = Regex.Matches(ResStr1, re, options);
                for (int i = 0; i < mc.Count; i++)
                {
                    Match match = mc[i];
                    CarMarketInfo carMarketInfo = new CarMarketInfo 
                    {
                        CarId = int.Parse(match.Result("${carId}")),
                        CarName = match.Result("${carName}"),
                        CarPrice = int.Parse(match.Result("${carPrice}"))
                    };
                    carMarketInfos.Add(carMarketInfo);
                }

                int pagenum = lastPageStart / 8;

                for (int i = 1; i <= pagenum; i++)
                {
                    if (i + 1 < mc.Count)
                        Thread.Sleep(delayConnect * 1000);

                    url = string.Format("http://www.kaixin001.com/app/app.php?aid=1040&url=market.php&start={0}", (i * 8).ToString());
                    hp = new HttpProc(url, cc);
                    ResStr1 = hp.Proc();
                    mc = Regex.Matches(ResStr1, re, options);
                    for (int j = 0; j < mc.Count; j++)
                    {
                        Match match = mc[j];
                        CarMarketInfo carMarketInfo = new CarMarketInfo
                        {
                            CarId = int.Parse(match.Result("${carId}")),
                            CarName = match.Result("${carName}"),
                            CarPrice = int.Parse(match.Result("${carPrice}"))
                        };
                        carMarketInfos.Add(carMarketInfo);
                    }
                }
            }
            return carMarketInfos;
        }

        //登录
        public bool Login(string email, string password)
        {
            Email = email;
            Password = password;
            if (UserInfo != null && UserInfo.AuthenticationCookieCollection != null)
            {
                cc = UserInfo.AuthenticationCookieCollection;
                try
                {
                    if (LoginNotifications != null)
                        LoginNotifications(this);

                    GetUserInfoByUid(UserInfo.uid);

                    if (LoginSuccessNotifications != null)
                        LoginSuccessNotifications(this);
                    return true;
                }
                catch(Exception ex)
                {
                    if (LoginFailureNotifications != null)
                        LoginFailureNotifications(this);

                    UserInfo.AuthenticationCookieCollection = null;
                    cc = null;
                    return Login(email,password);
                }
            }
            else
            {
                if (string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password))
                {
                    throw new ArgumentNullException("帐号或密码为空！");
                }

                if (LoginNotifications != null)
                    LoginNotifications(this);

                string url = "http://www.kaixin001.com/login/login.php";
                string postData = string.Format("url=%2F&email={0}&password={1}&invisible=1", Common.UrlEncode(email), Common.UrlEncode(password));

                HttpProc hp = new HttpProc(url, postData);
                string ResStr1 = hp.Proc();
                if (ResStr1.IndexOf("帐号或密码不太对吧") > 0)
                {
                    if (LoginFailureNotifications != null)
                        LoginFailureNotifications(this);

                    //可能情况：该帐号尚未完成注册步骤，请点击注册确认邮件的确认链接！点击这里重新发送确认邮件。
                    //尝试发送确认邮件，等待由kaixin_register_active_bygmail.exe激活
                    new HttpProc(string.Format(string.Format("http://www.kaixin001.com/reg/reg_mail.php?email={0}",Common.UrlEncode(email)))).Proc();

                    if (MessageNotifications != null)
                        MessageNotifications(this, string.Format("帐户登录失败：可能由于该帐号尚未完成注册步骤，尝试向{0}发送确认邮件", email));
                    return false;
                }
                else
                {
                    try
                    {
                        cc = hp.cookieGet;
                        string re = "<a\\s+href=\\\"/set/detail.php\\?uid=(?<uid>\\d+)\\\"\\s+class=\\\"sl\\\"\\s+title=\\\"个人资料\\\">个人资料</a>";
                        string uid = Regex.Match(ResStr1, re).Result("${uid}");
                        UserInfo = GetUserInfoByUid(uid);

                        if (LoginSuccessNotifications != null)
                            LoginSuccessNotifications(this);

                        //UserInfo.AuthenticationCookieCollection = cc;
                        return true;
                    }
                    catch(Exception ex)
                    {
                        if (LoginFailureNotifications != null)
                            LoginFailureNotifications(this);

                        if (MessageNotifications != null)
                            MessageNotifications(this, string.Format("登录过程中出现错误：{0}",ex.Message));

                        return false;
                    }
                }
           }
        }

        //添加挣车位组件
        public void InstallParkApp()
        {
            InstallApp("1040");
        }

        //添加组件
        public void InstallApp(string aid)
        {
            string url = string.Format("http://www.kaixin001.com/app/install.php?aid={0}&isinstall=1", aid);
            HttpProc hp = new HttpProc(url, cc);
            string ResStr1 = hp.Proc();
        }

        //添加场景 by sym
        public void InstallScen(string verify, int cardid)
        {
            string url = "http://www.kaixin001.com/parking/card_free_scene.php";
            string postData = string.Format("verify={0}&cardid={1}", verify, cardid);
            HttpProc hp = new HttpProc(url, postData, cc);
            string str = hp.Proc();
        }

        //发送添加好友请求
        public void SendAddFriendVerifyRequest(string uid)
        {
            string url = "http://www.kaixin001.com/friend/addverify.php";
            string postData = string.Format("from=&touid={0}&content=hheelloo~", uid);
            HttpProc hp = new HttpProc(url,postData, cc);
            string ResStr1 = hp.Proc();

            url = "http://www.kaixin001.com/friend/new.php";
            postData = string.Format("touid={0}", uid);
            new HttpProc(url, postData, cc).Proc();
        }

        //确认好友添加请求
        public void AgreeFriend(string uid, string smid)
        {
            string url = "http://www.kaixin001.com/friend/editfriend.php";
            string postData = string.Format("fuid={0}&byname=&memo=&groups=&allgroups=%E7%8E%B0%E5%9C%A8%E5%90%8C%E4%BA%8B%2C%E4%BB%A5%E5%89%8D%E5%90%8C%E4%BA%8B%2C%E5%A4%A7%E5%AD%A6%E5%90%8C%E5%AD%A6%2C%E9%AB%98%E4%B8%AD%E5%90%8C%E5%AD%A6%2C%E5%AE%B6%E4%BA%BA%E4%BA%B2%E6%88%9A%2C%E6%8C%9A%E4%BA%A4%E5%A5%BD%E5%8F%8B%2C%E6%99%AE%E9%80%9A%E6%9C%8B%E5%8F%8B%2C%E6%9C%8B%E5%8F%8B%E7%9A%84%E6%9C%8B%E5%8F%8B%2C%E5%85%B6%E4%BB%96&start=0&from=sysmsg&smid={1}", uid, smid);
            HttpProc hp = new HttpProc(url,postData, cc);
            string ResStr1 = hp.Proc();
        }

        //确认好友添加请求
        public IList<string> AgreeFriend(IList<string> uids, int delayConnect)
        {
            string url = "http://www.kaixin001.com/msg/sys.php";
            HttpProc hp = new HttpProc(url, cc);
            string ResStr1 = hp.Proc();
            string re = "<a\\s+href=\\\"javascript:agreefriend\\((?<uid>\\d+),\\s+(?<smid>\\d+)\\);\\\"\\s+class=\\\"sl\\\">同意</a>";
            if (Regex.IsMatch(ResStr1, re))
            {
                string re1 = "共(?<sysmessagecount>\\d+)条";
                int sysmessagecount = int.Parse(Regex.Match(ResStr1,re1).Result("${sysmessagecount}"));
                MatchCollection mc = Regex.Matches(ResStr1, re);
                for (int i = 0; i < mc.Count; i++)
                {
                    if (uids.Count == 0) break;
                    Match match = mc[i];
                    string uid = match.Result("${uid}");
                    string smid = match.Result("${smid}");
                    if (uids.Contains(uid))
                    {
                        AgreeFriend(uid, smid);
                        uids.Remove(uid);
                        if (i + 1 < mc.Count)
                            Thread.Sleep(delayConnect * 1000);
                    }
                }
                if (uids.Count > 0)
                {
                    int pagenum = sysmessagecount / 10;

                    for (int i = 1; i <= pagenum;i++)
                    {
                        url = string.Format("http://www.kaixin001.com/msg/sys.php?start={0}",(i * 10).ToString());
                        hp = new HttpProc(url, cc);
                        ResStr1 = hp.Proc();
                        mc = Regex.Matches(ResStr1, re);
                        for (int j = 0; j < mc.Count; j++)
                        {
                            if (uids.Count == 0) break;
                            Match match = mc[j];
                            string uid = match.Result("${uid}");
                            string smid = match.Result("${smid}");
                            if (uids.Contains(uid))
                            {
                                AgreeFriend(uid, smid);
                                uids.Remove(uid);
                                if (j + 1 < mc.Count)
                                    Thread.Sleep(delayConnect * 1000);
                            }
                        }
                    }
                }
            }
            return uids;
        }

        public string SendGift(string uid, int gid, int quiet, int anon, string content,string texttype)
        {
            string url = "http://www.kaixin001.com/gift/send.php";
            string postData = string.Format("reveuid={0}&&gid={1}&quiet={2}&anon={3}&content={4}&texttype={5}",
                uid, gid.ToString(), quiet.ToString(), anon.ToString(), Common.UrlEncode(content), texttype);
            HttpProc hp = new HttpProc(url, postData,cc);
            string re = "\\{\\\"result\\\":(?<result>\\d+),\\\"word\\\":\\\"(?<word>.*?)\\\"\\}";
            string ResStr1 = hp.Proc();
            if (Regex.IsMatch(ResStr1, re))
            {
                Match match = Regex.Match(ResStr1, re);
                SendGiftMessageInfo sendGiftMessageInfo = new SendGiftMessageInfo
                {
                    Result = int.Parse(match.Result("${result}")),
                    Word = Common.utf8(match.Result("${word}"))
                };
                if (sendGiftMessageInfo.Result == 1)
                    return "礼物已送出！";
                else
                    return sendGiftMessageInfo.Word;
            }
            else
                return string.Empty;
        }

        //获取用户信息
        public UserInfo GetUserInfoByUid(string uid)
        {
            UserInfo userInfo = new UserInfo();
            string url = string.Format("http://www.kaixin001.com/interface/user.php?uid={0}", uid);
            HttpProc hp = new HttpProc(url, cc);
            string ResStr1 = hp.Proc();
            string re = @"\{\""uid\"":(?<uid>\d+),\""real_name\"":\""(?<real_name>.*?)\"",\""nick\"":\""(?<nick>.*?)\"",\""gender\"":\""(?<gender>\d+)\"",\""logo120\"":\""(?<logo120>.*?)\"",\""logo50\"":\""(?<logo50>.*?)\"",\""logo25\"":\""(?<logo25>.*?)\"",\""hometown\"":\""(?<hometown>.*?)\"",\""city\"":\""(?<city>.*?)\"",\""isfriend\"":(?<isfriend>\d+),\""commentright\"":(?<commentright>\d+)\}";
            if (Regex.IsMatch(ResStr1, re))
            {
                Match match = Regex.Match(ResStr1, re);
                userInfo = new UserInfo
                {
                    uid = match.Result("${uid}"),
                    real_name = Common.utf8(match.Result("${real_name}")),
                    nick = Common.utf8(match.Result("${nick}")),
                    gender = match.Result("${gender}"),
                    logo120 = Regex.Unescape(match.Result("${logo120}")),
                    logo50 = Regex.Unescape(match.Result("${logo50}")),
                    logo25 = Regex.Unescape(match.Result("${logo25}")),
                    hometown = Common.utf8(match.Result("${hometown}")),
                    city = Common.utf8(match.Result("${city}")),
                    isfriend = int.Parse(match.Result("${isfriend}")),
                    commentright = int.Parse(match.Result("${commentright}")),
                };
            }
            else
                throw new Exception("error！");
            return userInfo;
        }

        //退出系统（无需执行本操作，注释掉）
        public void Logout()
        {
            //string url = "http://www.kaixin001.com/login/logout.php";
            //HttpProc hp = new HttpProc(url, cc);
            //hp.Proc();
            if (LogoutNotifications != null)
                LogoutNotifications(this);
        }

        //获取好友列表
        public IList<SimpleUserInfo> GetAllUserInfos()
        {
            IList<SimpleUserInfo> userInfos = new List<SimpleUserInfo>();
            string url = "http://www.kaixin001.com/interface/suggestfriend.php?pars=gf_me&type=all";
            HttpProc hp = new HttpProc(url, cc);
            string ResStr1 = hp.Proc();

            string re = "\\{\\\"uid\\\":(?<uid>\\d+),\\\"real_name\\\":\\\"(?<real_name>.*?)\\\",\\\"real_name_unsafe\\\":\\\"(?<real_name_unsafe>.*?)\\\"\\}";
            MatchCollection mc = Regex.Matches(ResStr1, re);
            for (int i = 0; i < mc.Count; i++)
            {
                Match match = mc[i];
                SimpleUserInfo userInfo = new SimpleUserInfo
                {
                    uid = match.Result("${uid}"),
                    real_name = Common.utf8(match.Result("${real_name}")),
                    real_name_unsafe = Common.utf8(match.Result("${real_name_unsafe}")),
                };
                if(userInfo.uid != UserInfo.uid)
                    userInfos.Add(userInfo);
            }
            return userInfos;
        }

        //获取群组下好友列表
        public IList<SimpleUserInfo> GetUserInfosByGroup(string groupName)
        {
            IList<SimpleUserInfo> userInfos = new List<SimpleUserInfo>();
            string url = string.Format("http://www.kaixin001.com/interface/suggestfriend.php?type=all&group={0}&pars=gf_me", groupName);
            HttpProc hp = new HttpProc(url, cc);
            string ResStr1 = hp.Proc();

            string re = "\\{\\\"uid\\\":(?<uid>\\d+),\\\"real_name\\\":\\\"(?<real_name>.*?)\\\",\\\"real_name_unsafe\\\":\\\"(?<real_name_unsafe>.*?)\\\"\\}";
            MatchCollection mc = Regex.Matches(ResStr1, re);
            for (int i = 0; i < mc.Count; i++)
            {
                Match match = mc[i];
                SimpleUserInfo userInfo = new SimpleUserInfo
                {
                    uid = match.Result("${uid}"),
                    real_name = Common.utf8(match.Result("${real_name}")),
                    real_name_unsafe = Common.utf8(match.Result("${real_name_unsafe}")),
                };
                userInfos.Add(userInfo);
            }
            return userInfos;
        }

        //删除好友关系
        public void DeleteFriend(SimpleUserInfo userInfo)
        {
            string url = "http://www.kaixin001.com/friend/del.php";//?touid={0}", userInfo.uid);
            string postData = string.Format("touid={0}", userInfo.uid);
            HttpProc hp = new HttpProc(url, postData,cc);
            string s = hp.Proc();
        }

        //获取群组列表
        public IList<GroupInfo> GetGroupInfos()
        {
            IList<GroupInfo> groupInfos = new List<GroupInfo>();

            string url = "http://www.kaixin001.com/interface/fgroup.php";
            HttpProc hp = new HttpProc(url, cc);
            string ResStr1 = hp.Proc();

            string re = "\\\"(?<groupname>.*?)\\\"";
            MatchCollection mc = Regex.Matches(ResStr1, re);
            for (int i = 0; i < mc.Count; i++)
            {
                Match match = mc[i];
                GroupInfo groupInfo = new GroupInfo
                {
                    Name = Common.utf8(match.Result("${groupname}"))
                };
                groupInfos.Add(groupInfo);
            }
            return groupInfos;
        }

        public bool CheckAppForbided()
        {
            string url = "http://www.kaixin001.com/app/app.php?aid=1040";
            HttpProc hp = new HttpProc(url, cc);
            return hp.Proc().Contains("禁止使用此组件");
        }

        public IList<AppInfo> GetAppInfos()
        {
            IList<AppInfo> appInfos = new List<AppInfo>();

            string url = "http://www.kaixin001.com/app/list.php";
            HttpProc hp = new HttpProc(url, cc);
            string ResStr1 = hp.Proc();

            string re = @"<div\s+class=\""p10\"">.*?<img\s+src=\""(?<appimg>.*?)\"".*?/>.*?
<p><a\s+href=\""/app/\?aid=(?<appid>\d+)\""\s+class=\""sl2\""><b\s+class=\""f14\"">(?<appname>.*?)</b></a></p>\s+
<p>(?<appdescription>.*?)</p>\s+
<p\s+class=\""c9\"">开发者：(?<appauthor>.*?)</p>\s+
(.*?共添加：(?<appaddcount>\d+)人)?";
            RegexOptions options = ((RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline) | RegexOptions.IgnoreCase);

            MatchCollection mc = Regex.Matches(ResStr1, re, options);
            for (int i = 0; i < mc.Count; i++)
            {
                Match match = mc[i];
                AppInfo appInfo = new AppInfo
                {
                    Id = match.Result("${appid}"),
                    Name = match.Result("${appname}"),
                    Img = match.Result("${appimg}"),
                    Description = match.Result("${appdescription}"),
                    AddCount = int.Parse(match.Result("${appaddcount}")),
                    Author = match.Result("${appauthor}")
                };
                appInfos.Add(appInfo);
            }
            return appInfos;
        }

        public IList<GiftInfo> GetGiftInfos(ref int advGiftCount)
        {
            IList<GiftInfo> giftInfos = new List<GiftInfo>();
            
            string url = "http://www.kaixin001.com/gift/";
            HttpProc hp = new HttpProc(url, cc);
            string ResStr1 = hp.Proc();
            string giftre = "<input\\s+type=\\\"radio\\\"\\s+name=\\\"gid\\\"\\s+value=\\\"(?<gid>\\d+)\\\"\\s+/></div>\\s+<div." +
"*?><img.*?alt=\\\"(?<gifname>.*?)\\\".*?/></div>\\s+<div.*?></div>";

            string advgiftre = "<div.*?id=\\\"advgiftpage_\\d+\\\".*?>.*?\r\n(<div.*?>\\s*<input.*?value=\\\"(?<advgid>\\d+)" +
"\\\".*?/></div>\\s+<div.*?><img.*?alt=\\\"(?<advgifname>.*?)\\\".*?/></div>\\s+</div>\\s*" +
")+.*?\r\n</div>";
            RegexOptions options = ((RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline) | RegexOptions.IgnoreCase);

            if (Regex.IsMatch(ResStr1, giftre, options))
            {
                MatchCollection mc = Regex.Matches(ResStr1, giftre, options);
                for (int i = 0; i < mc.Count; i++)
                {
                    Match match = mc[i];
                    for (int j = 0; j < match.Groups["gid"].Captures.Count; j++)
                    {
                        giftInfos.Add(new GiftInfo 
                        {
                            Id = int.Parse(match.Groups["gid"].Captures[j].Value),
                            Name = match.Groups["gifname"].Captures[j].Value,
                            GiftType = GiftType.普通礼物
                        });
                    }
                }
            }

            options = ((RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline) | RegexOptions.IgnoreCase);

            if (Regex.IsMatch(ResStr1, advgiftre, options))
            {
                MatchCollection mc = Regex.Matches(ResStr1, advgiftre, options);
                for (int i = 0; i < mc.Count; i++)
                {
                    Match match = mc[i];
                    for (int j = 0; j < match.Groups["advgid"].Captures.Count; j++)
                    {
                        giftInfos.Add(new GiftInfo
                        {
                            Id = int.Parse(match.Groups["advgid"].Captures[j].Value),
                            Name = match.Groups["advgifname"].Captures[j].Value,
                            GiftType = GiftType.高级礼物
                        });
                    }
                }
            }

            string re = @"var\s*v_advcount\s*=\s*parseInt\(\""(?<advgiftcount>\d+)\""\)";
            if (Regex.IsMatch(ResStr1, re))
                advGiftCount = int.Parse(Regex.Matches(ResStr1, re)[0].Result("${advgiftcount}"));

            return giftInfos;
        }

        public void SendMsg(string content, string texttype, string uids)
        {
            string url = "http://www.kaixin001.com/msg/post.php";
            string postData = string.Format("content={0}&texttype={1}&uids={2}",  Common.UrlEncode(content), texttype, uids);
            HttpProc hp = new HttpProc(url, postData, cc);
            string str = hp.Proc();
        }

        public int GetSceneMinute()
        {
            string url = "http://www.kaixin001.com/app/app.php?aid=1040";
            HttpProc hp = new HttpProc(url, cc);
            string ResStr1 = hp.Proc();
            string re = @"var\s+v_userdata\s+=\s+.*?money_minute\"":\""(?<money_minute>\d+)\""";
            if (Regex.IsMatch(ResStr1, re))
            {
                return int.Parse(Regex.Match(ResStr1, re).Result("${money_minute}"));
            }
            else
                return 10;
        }

        public MyTeamInfo GetMyTeamInfo(ref string verify)
        {
            MyTeamInfo myTeamInfo = new MyTeamInfo();
            IList<TeamInfo> teamInfos = new List<TeamInfo>();
            string url = "http://www.kaixin001.com/app/app.php?aid=1040&url=myteam.php";
            HttpProc hp = new HttpProc(url, cc);
            string ResStr1 = hp.Proc();

            string reverify = "var\\s+g_verify\\s*=\\s*\\\"(?<g_verify>.*?)\\\"";
            if (Regex.IsMatch(ResStr1, reverify))
            {
                verify = Regex.Match(ResStr1, reverify).Result("${g_verify}");
            }

            string re = @"<div\s+class=\""l\""\s+style=\""width:650px;\"">(?<teaminfo>.*?)\s+<div.*?>第(?<teamday>\d+)天</div>\s+
<div.*?>(&nbsp;|(?<canoil>.*?))</div>\s+<div.*?><a\s+class=\""sl\""\s+href=\""javascript:matchDetail\(\s*(?<matchuid>\d+)\s*,\s*(?<matchid>\d+)\s*\);\"">查看赛况";

            string re1 = @"(<a\s+class=sl\s+href=\""javascript:team\(\s*(?<uid>\d+)\s*,\s*'(?<rname>.*?)'\s*\);\"">.*?</a>(\s*\-\s*)?)+的(?<carteam>.*?)(\s*<img|</div>)";
            if (Regex.IsMatch(ResStr1, re, options))
            {
                MatchCollection mc = Regex.Matches(ResStr1, re, options);
                for (int i = 0; i < mc.Count; i++)
                {
                    Match match = mc[i];
                    TeamInfo teamInfo = new TeamInfo
                    {
                        info = Common.FilterHtml(match.Result("${teaminfo}")),
                        teamday = int.Parse(match.Result("${teamday}")),
                        canoil = match.Result("${canoil}").Length > 0,
                        matchuid = int.Parse(match.Result("${matchuid}")),
                        matchid = int.Parse(match.Result("${matchid}"))
                    };
                    if (Regex.IsMatch(match.Result("${teaminfo}"), re1,options))
                    {
                        MatchCollection mc1 = Regex.Matches(match.Result("${teaminfo}"), re1, options);
                        for (int j = 0; j < mc1.Count; j++)
                        {
                            Match match2 = mc1[j];
                            CarTeamInfo carTeamInfo = new CarTeamInfo
                            {
                                CarTeamName = match2.Result("${carteam}")
                            };
                            for (int k = 0; k < match2.Groups["uid"].Captures.Count; k++)
                            {
                                carTeamInfo.SimpleUserInfos.Add(new SimpleUserInfo
                                {
                                    uid = match2.Groups["uid"].Captures[k].Value,
                                    real_name = match2.Groups["rname"].Captures[k].Value
                                });
                            }
                            teamInfo.CarTeamInfos.Add(carTeamInfo);
                        }
                    }
                    teamInfos.Add(teamInfo);
                }
            }
            myTeamInfo.TeamInfos = teamInfos;
            string re2 = "<a\\s+href=\\\"javascript:matchDetail\\(\\s*(?<matchuid>\\d+)\\s*,\\s*(?<matchid>\\d+)\\s*\\);";
            if (Regex.IsMatch(ResStr1, re2, options))
            {
                Match match = Regex.Match(ResStr1, re2, options);
                myTeamInfo.MyCarTeamInfo = new MyCarTeamInfo
                {
                    matchuid = int.Parse(match.Result("${matchuid}")),
                    matchid = int.Parse(match.Result("${matchid}"))
                };
                string re3 = "<div\\s+class=\\\"dc_bor\\\"><img.*?>\\s+<b>(?<mycarteamname>.*?)：\\s*";
                if (Regex.IsMatch(ResStr1, re3, options))
                {
                    Match match1 = Regex.Match(ResStr1, re3, options);
                    myTeamInfo.MyCarTeamInfo.CarTeamName = match1.Result("${mycarteamname}");
                    myTeamInfo.MyCarTeamInfo.UnionFlag = myTeamInfo.MyCarTeamInfo.CarTeamName.Contains("联合车队");
                    if (myTeamInfo.MyCarTeamInfo.UnionFlag)
                    {
                        string re4 = @"javascript:teamBreakUni\(\s*(?<teamid>\d+)\s*\);";
                        if (Regex.IsMatch(ResStr1, re4, options))
                        {
                            myTeamInfo.MyCarTeamInfo.TeamId = int.Parse(Regex.Match(ResStr1, re4, options).Result("${teamid}"));
                        }
                    }
                    else
                    {
                        string re4 = @"javascript:teamDismiss\(\s*(?<teamid>\d+)\s*\);";
                        if (Regex.IsMatch(ResStr1, re4, options))
                        {
                            myTeamInfo.MyCarTeamInfo.TeamId = int.Parse(Regex.Match(ResStr1, re4, options).Result("${teamid}"));
                        }

                    }
                }
            }
            else 
            {
                re2 = "<a\\s+href=\\\"javascript:matchOrigin\\(\\s*(?<teamid>\\d+)\\s*\\);";
                if (Regex.IsMatch(ResStr1, re2, options))
                {
                    Match match = Regex.Match(ResStr1, re2, options);
                    myTeamInfo.MyCarTeamInfo = new MyCarTeamInfo
                    {
                        TeamId = int.Parse(match.Result("${teamid}")),
                    };
                    string re3 = "<div\\s+class=\\\"dc_bor\\\"><img.*?>\\s+<b>(?<mycarteamname>.*?)：\\s*";
                    if (Regex.IsMatch(ResStr1, re3, options))
                    {
                        Match match1 = Regex.Match(ResStr1, re3, options);
                        myTeamInfo.MyCarTeamInfo.CarTeamName = match1.Result("${mycarteamname}");
                    }
                }
            }
            return myTeamInfo;
        }

        public IList<OilInfo> GetUserTeamOilInfos(int matchuid, int matchid)
        {
            IList<OilInfo> oilInfos = new List<OilInfo>();

            try
            {
                string url = string.Format("http://www.kaixin001.com/app/app.php?aid=1040&url=match.php&matchuid={0}&matchid={1}",
                    matchuid.ToString(), matchid.ToString());
                HttpProc hp = new HttpProc(url, cc);
                string ResStr1 = hp.Proc();
                string re = @"oil\(\s*(?<teamuid>\d+)\s*,\s*(?<teamid>\d+)\s*,\s*1";
                if (Regex.IsMatch(ResStr1, re, options))
                {
                    MatchCollection mc = Regex.Matches(ResStr1, re, options);
                    for (int i = 0; i < mc.Count; i++)
                    {
                        Match match = mc[i];
                        OilInfo oilInfo = new OilInfo
                        {
                            teamuid = int.Parse(match.Result("${teamuid}")),
                            teamid = int.Parse(match.Result("${teamid}"))
                        };
                        oilInfos.Add(oilInfo);
                    }
                }
            }
            catch (Exception ex)
            {
 
            }

            return oilInfos;
        }

        public JourneyInfo GetJourneyInfo(int matchuid, int matchid)
        {
            JourneyInfo journeyInfo = new JourneyInfo();

            try
            {
                string url = string.Format("http://www.kaixin001.com/app/app.php?aid=1040&url=match.php&matchuid={0}&matchid={1}",
                    matchuid.ToString(), matchid.ToString());
                HttpProc hp = new HttpProc(url, cc);
                string ResStr1 = hp.Proc();
                string re1 = "总长(?<totaljourney>\\d+)km";
                int totalJourney = 0;
                if (Regex.IsMatch(ResStr1, re1, options))
                {
                    journeyInfo.TotalJourney = int.Parse(Regex.Match(ResStr1, re1, options).Result("${totaljourney}"));
                }

                string re = "(?<teamname>\\w+)车队<br\\s+/>(?<matchstatus>.*?)<br\\s+/>(?<journey>\\d+)km";
                if (Regex.IsMatch(ResStr1, re, options))
                {
                    MatchCollection mc = Regex.Matches(ResStr1, re, options);
                    for (int i = 0; i < mc.Count; i++)
                    {
                        Match match = mc[i];

                        CarTeamJourneyInfo carTeamJourneyInfo = new CarTeamJourneyInfo
                        {
                            CarTeamName = match.Result("${teamname}"),
                            MatchStatus = match.Result("${matchstatus}"),
                            Journey = int.Parse(match.Result("${journey}"))
                        };
                        journeyInfo.CarTeamJourneyInfos.Add(carTeamJourneyInfo);
                    }
                }
            }
            catch (Exception ex)
            {

            }

            return journeyInfo;
        }

        public OilInfo GetTeamBeginOilInfo(int matchuid, int matchid,out bool team_already_begin_flag)
        {
            team_already_begin_flag = false;

            OilInfo oilInfo = null;

            string url = Team.GetOilLink(matchuid, matchid);
            HttpProc hp = new HttpProc(url, cc);
            string ResStr1 = hp.Proc();
            string re = @"javascript:teamBegin\(\s*(?<teamuid>\d+)\s*,\s*(?<teamid>\d+)\s*\);";
            if (Regex.IsMatch(ResStr1, re, options))
            {
                Match match = Regex.Match(ResStr1, re, options);
                oilInfo = new OilInfo
                {
                    teamuid = int.Parse(match.Result("${teamuid}")),
                    teamid = int.Parse(match.Result("${teamid}"))
                };
            }

            if (ResStr1.Contains("你的车队今天已经启动"))
                team_already_begin_flag = true;

            return oilInfo;
        }
    }
}
